<template>
  <div class='container' style="padding: 20px;">
    <el-card>
      <p class="title">{{tile}}</p>
      <el-form ref="form" class="form" :model="formData" :rules="rules">
        <!-- 学科 -->
        <el-form-item label="学科：" prop="subjectID">
            <el-select placeholder="请选择" style="width: 400px;" v-model="formData.subjectID" @change="changesubjectID">
              <el-option
              v-for="(item,index) in subjectIDlist" :key="index"
              :label="item.label"
              :value="item.value"
              ></el-option>
            </el-select>
        </el-form-item>
         <!-- 目录 -->
        <el-form-item label="目录：" prop="catalogID">
            <el-select placeholder="请选择" style="width: 400px;" v-model="formData.catalogID">
              <el-option
              v-for="(item,index) in catalogIDlist" :key="index"
              :label="item.label"
              :value="item.value"
              ></el-option>
            </el-select>
        </el-form-item>
         <!-- 企业 -->
        <el-form-item label="企业：" prop="enterpriseID">
            <el-select placeholder="请选择" style="width: 400px;" v-model="formData.enterpriseID">
              <el-option
              v-for="item in enterpriselist" :key="item.id"
              :label="item.company"
              :value="item.creatorID"
              ></el-option>
            </el-select>
        </el-form-item>
        <!-- 城市 -->
        <el-form-item label="城市：" prop="province">
            <el-select placeholder="请选择" style="width:195px;" v-model="formData.province" @change="provincechange" >
              <el-option
              v-for="item in provincelist" :key="item"
                :label="item"
                :value="item"
                ></el-option>
            </el-select>
            <el-select placeholder="请选择" style="width:195px; margin-left: 10px;" v-model="formData.city" >
              <el-option
              v-for="item in citylist" :key="item"
                :label="item"
                :value="item"
                ></el-option>
            </el-select>
        </el-form-item>
        <!-- 方向 -->
        <el-form-item label="方向：" prop="direction">
            <el-select placeholder="请选择" style="width:400px;" v-model="formData.direction">
              <el-option
              v-for="item in directionlist" :key="item"
                :label="item"
                :value="item"
                ></el-option>
            </el-select>
        </el-form-item>
        <!-- 题型 -->
        <el-form-item label="题型：" prop="questionType">
          <el-radio
          @change="questionTypelabel"
          v-for="item in questionTypelist" :key="item.value"
           :label="item.value+''"
           v-model="formData.questionType"
           >{{item.label}}</el-radio>
        </el-form-item>
        <!-- 难度 -->
        <el-form-item label="难度：" prop="difficulty">
          <el-radio
          v-for="item in difficultylist" :key="item.value"
           :label="item.value+''"
           v-model="formData.difficulty"
           >{{item.label}}</el-radio>
        </el-form-item>
        <!-- 题干 -->
        <el-form-item label="题干：" prop="question">
          <quill-editor class="quill-editor" v-model="formData.question"></quill-editor>
        </el-form-item>
        <!-- 选项 -->
        <el-form-item label="选项：" prop="options" v-if="formData.questionType !== '3' " >
         <div class="optionBox"  v-for="(item,index) in formData.options" :key="index" >
             <el-radio :label="true" v-if="formData.questionType === '1'" v-model="item.isRight" @change="radio(item)" style="margin-right:0">{{item.letter}}：
             </el-radio>
            <el-checkbox  v-if="formData.questionType === '2' " :label="true" style="margin-right:0" v-model="item.isRight" >{{item.letter}}：
            </el-checkbox>
               <el-input size="mini" v-model="item.title" style="width:240px"></el-input>
             <el-upload
              class="imgbox"
              action="https://jsonplaceholder.typicode.com/posts/"
              :headers="{'Authorization':'Bearer '+ token}"
              :on-success="(res,file)=>{uploadSuccess(item,res,file)}"
              :show-file-list="false">
              <img v-if="item.img" :src="item.img" class="avatar">
              <span v-else>上传图片</span>
              <i class="el-icon-circle-close"></i>
            </el-upload>
         </div>
           <!-- 新增选项与答案 -->
        <el-button
        :disabled="formData.questionType !== '2' "
        type="danger" size="small"
        @click="addList"
        style="margin-left: 60px;"
        >+新增选项与答案</el-button>
        </el-form-item>
        <!-- 解析视频 -->
        <el-form-item label="解析视频：" prop="videoURL" style="margin-left: -20px;">
          <el-input style="width:400px" v-model="formData.videoURL"></el-input>
        </el-form-item>
        <!-- 答案解析 -->
         <el-form-item label="答案解析：" prop="answer" style="margin-left: -28px;">
          <quill-editor class="quill-editor" style="margin-left:90px;" v-model="formData.answer"></quill-editor>
        </el-form-item>
         <!-- 题目备注 -->
        <el-form-item label="题目备注：" prop="remarks" style="margin-left: -20px;">
          <el-input style="width:400px;"  type="textarea" v-model="formData.remarks"></el-input>
        </el-form-item>
         <!-- 试题标签 -->
         <el-form-item label="试题标签：" prop="tags" style="margin-left: -20px;">
            <el-select
              v-model="formData.tags"
              style="width: 400px;"
              multiple
              filterable
              allow-create
              default-first-option
              placeholder="请选择试题标签">
              <el-option
              v-for="item in tagsList" :key="item.value"
                :label="item.label"
                :value="item.label">
              </el-option>
            </el-select>
         </el-form-item>
         <el-button type="primary" v-if="modify" @click="sendout" style="margin-left:60px ;">确认提交</el-button>
         <el-button type="success" v-else @click="modifysendout" style="margin-left:60px ;">确认修改</el-button>
      </el-form>
    </el-card>
  </div>
</template>
<script>
import { simple } from '@/api/hmmm/subjects'
import { simple as getcatalogue } from '@/api/hmmm/directorys'
import { list } from '@/api/hmmm/companys'
import { provinces, citys } from '@/api/hmmm/citys'
import { direction, questionType, difficulty } from '@/api/hmmm/constants'
import { getToken } from '@/utils/auth'
import { simple as simplelist } from '@/api/hmmm/tags'
import { add, detail, update } from '../../api/hmmm/questions'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

import { quillEditor } from 'vue-quill-editor'
export default {
  name: 'questions',
  components: {
    quillEditor
  },
  data () {
    return {
      subjectIDlist: [], // 学科列表
      catalogIDlist: [], // 目录列表
      enterpriselist: [], // 企业列表
      provincelist: provinces(), // 城市列表
      citylist: [], // 地区列表
      directionlist: [], // 获取方向列表
      questionTypelist: [], // 题型列表
      difficultylist: [], // 难度列表
      token: getToken(), // token--存储图片
      tagsList: [], // 试题标签列表
      tile: '试题录入',
      modify: true,
      // form 表单的数据
      formData: {
        subjectID: '', // 学科  发送请求前将它转成字符串
        catalogID: null, // 目录
        enterpriseID: null, // 企业
        province: '', // 城市
        city: '', // 地区
        direction: '', // 方向
        questionType: '1', // 题型
        difficulty: '1', // 难度
        question: '', // 题干
        videoURL: '', // 解析视频
        answer: '', // 答案解析
        remarks: '', // 题目备注
        tags: '', // 试题标签
        // 上传图片递增部分
        options: [
          { code: false, img: '', letter: 'A', title: '', isRight: false },
          { code: false, img: '', letter: 'B', title: '', isRight: false },
          { code: false, img: '', letter: 'C', title: '', isRight: false },
          { code: false, img: '', letter: 'D', title: '', isRight: false }
        ]

      },
      // 表单校验
      rules: {
        subjectID: [
        // 学科
          { required: true, message: '请输入学科名称', trigger: ['blur', 'change'] }
        ],
        catalogID: [
        // 目录
          { required: true, message: '请输入目录名称', trigger: ['blur', 'change'] }
        ],
        enterpriseID: [
        // 企业
          { required: true, message: '请输入企业名称', trigger: ['blur', 'change'] }
        ],
        // 地区
        province: [
          { required: true, message: '请输入地区名称', trigger: ['blur', 'change'] }
        ],
        // 方向
        direction: [
          { required: true, message: '请输入方向名称', trigger: ['blur', 'change'] }
        ],
        // 题型
        questionType: [
          { required: true, message: '请输入题型名称', trigger: ['blur', 'change'] }
        ],
        // 难度
        difficulty: [
          { required: true, message: '请输入难度名称', trigger: ['blur', 'change'] }
        ],
        // 题干
        question: [
          { required: true, message: '请输入题干名称', trigger: ['blur', 'change'] }
        ],
        // 答案解析
        answer: [
          { required: true, message: '请输入答案解析名称', trigger: ['blur', 'change'] }
        ]
      }
    }
  },
  created () {
    this.subjectIDsimple() // 获取学科列表
    this.getenterpriselist() // 获取企业列表
    this.directionlist = direction // 获取方向列表
    this.questionTypelist = questionType // 获取题型列表
    this.difficultylist = difficulty // 获取难度列表
    // console.log(this.$router)
    // 判断用户是否从精选题库并且携带id
    if (this.$route.query.id) {
      console.log(this.$route.query.id)
      this.getroute()
      this.tile = '修改目录'
      this.modify = false
    }
  },
  methods: {
    // 获取学科列表
    async subjectIDsimple () {
      const { data } = await simple()
      this.subjectIDlist = data
    },
    // 获取目录列表
    async changesubjectID () {
      console.log(this.enterpriselist)
      this.formData.catalogID = ''
      const { data } = await getcatalogue(this.formData)
      // console.log(res)
      this.catalogIDlist = data
      // 获取试题标签
      const res = await simplelist(this.formData)
      // console.log(res)
      this.tagsList = res.data
      // console.log(this.tagsList)
    },
    // 获取企业列表
    async getenterpriselist () {
      const { data: { items } } = await list()
      this.enterpriselist = items
      // console.log(this.enterpriselist)
    },
    // 获取地区列表
    provincechange () {
      this.formData.city = ''
      // console.log(this.formData.province)
      this.citylist = citys(this.formData.province)
    },
    radio (value) {
      // console.log(value)
      this.formData.options.forEach(v => {
        v.isRight = false
      })
      value.isRight = true
    },
    uploadSuccess (item, res, file) {
      // console.log(res)
      item.img = URL.createObjectURL(file.raw)
      console.log(file.raw)
    },
    questionTypelabel () {
      // console.log(1)
      this.formData.options.forEach(v => {
        // console.log(v)
        v.isRight = false
      })
    },
    // 添加多选框
    addList () {
      const arr = []
      this.formData.options.forEach(v => {
        const str = v.letter
        arr.push(str)
      })
      console.log(arr)
      arr.push(String.fromCharCode(arr.length + 65))
      // console.log(arr)
      // 获取到数组的最后一项 转成字符串
      const abc = arr.slice(-1).toString()
      this.formData.options.push({
        code: false, img: '', letter: abc, title: '', isRight: false
      })
    },
    // 添加试题
    sendout () {
      // console.log(2131)
      // 预交验
      this.$refs.form.validate(async boo => {
        // console.log(boo)
        // 发送请求
        // console.log(this.formData.tags.toString())
        if (boo) {
          const res = await add({ ...this.formData, tags: this.formData.tags.toString() })
          console.log(res.status)
          if (res.status !== 200) return this.$message.error('添加失败')
          this.$message.success('添加成功')
          // 清空表单
          this.$refs.form.resetFields()
          // 跳转页面
          this.$router.push('/questions/list')
        }
      })
    },
    // 回显
    async getroute () {
      const { data } = await detail({ id: this.$route.query.id })
      data.options.forEach(v => {
        if (v.isRight === 1) {
          v.isRight = true
        }
        this.formData = { ...data, tags: data.tags.split(',') }
      })
      this.$nextTick(() => {
        window.scrollTo(0, 0) // 置顶
      })
    },
    modifysendout () {
      // console.log(1231)
      // 预交验
      this.$refs.form.validate(async boo => {
        if (boo) {
          const res = await update(this.formData)
          console.log(res)
          if (res.status !== 200) this.$message.error('修改失败')
          this.$message.success('修改成功')
          //  回到修改页面
          this.$router.push('/questions/choice')
        }
      })
    }

  }
}
</script>

<style lang="scss" scoped>
  .container{
    ::v-deep .el-card__body{
    padding: 0;
    padding-right:30px ;
    padding-bottom: 40px;
  }
  }
  .title{
    border-bottom: 1px solid #ebeef5;
    padding: 0 18px 15px ;
  }
  .form{
    padding-top:5px ;
    padding-left: 70px ;
  }
   .quill-editor{
    height: 250px;
    margin: 10px 0 50px 60px;
  }
  .optionBox{
    padding-top:10px ;
    position: relative;
    margin-left: 60px;
    width: 400px;
    margin-bottom: 30px;
    // background-color: pink;
    .radiobox{
      margin-top: 15px;
    }
    .imgbox{
      position: relative;
      position: absolute;
      display: inline-block;
      width: 100px;
      height: 60px;
      margin-left:10px ;
      border: 1px dotted #ccc;
      top:0px;
      border-radius:5px ;
      text-align: center;
      line-height: 58px;
      .el-icon-circle-close{
        position: absolute;
        top: -10px;
        right: -10px;
        font-size: 20px;
        color: #ccc;
        background-color: #fff;
      }
    }
    .imgbox:hover{
      border: 1px dotted blue;
    }
    .avatar {
  width: 100px;
  height: 60px;
  display: block;
  overflow: hidden;
}
  }
</style>
